<template>
    <div class="app-container">
        <el-form v-show="showSearch" ref="queryForm" :model="queryParams" :inline="true">
            <el-form-item :label="$t('role.orderName')" prop="name">
                <el-input
                        v-model="queryParams.name"
                        :placeholder="$t('role.orderNameInput')"
                        clearable
                        size="small"
                        @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item :label="$t('program.status')" prop="status">
                <el-select v-model="queryParams.status" :placeholder="$t('role.orderStatus')" clearable size="small">
                    <el-option
                            v-for="dict in statusOptions"
                            :key="dict.value"
                            :label="dict.label"
                            :value="dict.value"
                    />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{
                    $t('elButton.search') }}
                </el-button>
                <el-button icon="el-icon-refresh-right" size="mini" @click="resetQuery">{{ $t('elButton.reset') }}
                </el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                        v-hasPerm="['menu_add']"
                        type="primary"
                        icon="el-icon-plus"
                        size="mini"
                        @click="handleAdd"
                >{{ $t('elButton.add') }}
                </el-button>
            </el-col>
            <div class="top-right-btn">
                <el-tooltip class="item" effect="dark" :content="$t('elButton.refresh')" placement="top">
                    <el-button size="mini" circle icon="el-icon-refresh" @click="handleQuery"/>
                </el-tooltip>
                <el-tooltip class="item" effect="dark"
                            :content="showSearch ? $t('elButton.hideSearch') : $t('elButton.showSearch')"
                            placement="top">
                    <el-button size="mini" circle icon="el-icon-search" @click="showSearch=!showSearch"/>
                </el-tooltip>
            </div>
        </el-row>

        <el-table
                v-loading="loading"
                :data="menuList"
                row-key="id"
                :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
        >
            <el-table-column prop="name" :label="$t('role.orderName')" :show-overflow-tooltip="true" width="160"/>
            <el-table-column prop="icon" :label="$t('role.icon')" align="center" width="100">
                <template slot-scope="scope">
                    <svg-icon :icon-class="scope.row.icon || ''"/>
                </template>
            </el-table-column>
            <el-table-column prop="sort" :label="$t('mechanism.sort')" width="60"/>
            <el-table-column prop="perms" :label="$t('role.authorityIdentification')" :show-overflow-tooltip="true"/>
            <el-table-column prop="component" :label="$t('role.componentPath')" :show-overflow-tooltip="true"/>
            <el-table-column prop="status" :label="$t('program.status')" :formatter="statusFormat" width="80"/>
            <el-table-column :label="$t('elButton.establishTime')" align="center" prop="createTime">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.createTime) }}</span>
                </template>
            </el-table-column>
            <el-table-column :label="$t('equipment.control')" align="center" class-name="small-padding fixed-width"
                             width="200" fixed="right">
                <template slot-scope="scope">
                    <el-button
                            v-hasPerm="['menu_edit']"
                            size="mini"
                            type="text"
                            icon="el-icon-edit"
                            @click="handleEdit(scope.row)"
                    >{{ $t('elButton.change') }}
                    </el-button>
                    <el-button
                            v-hasPerm="['menu_add']"
                            size="mini"
                            type="text"
                            icon="el-icon-plus"
                            @click="handleAdd(scope.row)"
                    >{{ $t('elButton.add') }}
                    </el-button>
                    <el-button
                            v-hasPerm="['menu_del']"
                            size="mini"
                            type="text"
                            icon="el-icon-delete"
                            @click="handleDel(scope.row)"
                    >{{ $t('elButton.delete') }}
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 添加或修改菜单对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="720px" :modal-append-to-body="true" :append-to-body="true"
                   :close-on-click-modal="false">
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
                <el-row>
                    <el-col :span="24">
                        <el-form-item :label="$t('role.supeiorMenu')">
                            <treeselect
                                    v-model="form.parentId"
                                    :options="menuOptions"
                                    :normalizer="normalizer"
                                    :show-count="true"
                                    :placeholder="$t('role.supeiorMenuSelect')"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item :label="$t('role.menuStyle')" prop="type">
                            <el-radio-group v-model="form.type">
                                <el-radio label="M">{{ $t('role.menuStyle1') }}</el-radio>
                                <el-radio label="C">{{ $t('role.menuStyle2') }}</el-radio>
                                <el-radio label="F">{{ $t('role.menuStyle3') }}</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item v-if="form.type != 'F'" :label="$t('role.menuIcon')">
                            <el-popover
                                    placement="bottom-start"
                                    width="460"
                                    trigger="click"
                                    @show="$refs['iconSelect'].reset()"
                            >
                                <IconSelect ref="iconSelect" @selected="selected"/>
                                <el-input slot="reference" v-model="form.icon" :placeholder="$t('role.iconSelect')"
                                          readonly>
                                    <svg-icon
                                            v-if="form.icon"
                                            slot="prefix"
                                            :icon-class="form.icon"
                                            class="el-input__icon"
                                            style="height: 40px;width: 16px;"
                                    />
                                    <i v-else slot="prefix" class="el-icon-search el-input__icon"/>
                                </el-input>
                            </el-popover>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item :label="$t('role.orderName')" prop="name">
                            <el-input v-model="form.name" :placeholder="$t('role.orderNameInput')"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item v-if="form.type != 'F'" :label="$t('role.routeAddress')" prop="path">
                            <el-input v-model="form.path" :placeholder="$t('role.routeAddressInput')"/>
                        </el-form-item>
                    </el-col>
                    <el-col v-if="form.type == 'C'" :span="12">
                        <el-form-item :label="$t('role.componentPath')" prop="component">
                            <el-input v-model="form.component" :placeholder="$t('role.componentPathInput')"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item v-if="form.type != 'M'" :label="$t('role.authorityIdentification')">
                            <el-input v-model="form.perms" :placeholder="$t('role.authorityIdentificationInput')"
                                      maxlength="50"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item :label="$t('mechanism.showSort')" prop="sort">
                            <el-input-number v-model="form.sort" controls-position="right" :min="0"/>
                        </el-form-item>
                    </el-col>
                    <el-col v-if="form.type == 'C'" :span="12">
                        <el-form-item :label="$t('mechanism.isCache')">
                            <el-radio-group v-model="form.noCache">
                                <el-radio
                                        v-for="dict in cacheOptions"
                                        :key="dict.value"
                                        :label="dict.value"
                                >{{ dict.label }}
                                </el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item v-if="form.type != 'F'" :label="$t('role.status')">
                            <el-radio-group v-model="form.status">
                                <el-radio
                                        v-for="dict in statusOptions"
                                        :key="dict.value"
                                        :label="dict.value"
                                >{{ dict.label }}
                                </el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">{{ $t('submitText') }}</el-button>
                <el-button @click="cancel">{{ $t('cancelText') }}</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
  import { listMenu, getMenu, delMenu, addMenu, editMenu } from '@/api/system/menu'
  import Treeselect from '@riophae/vue-treeselect'
  import '@riophae/vue-treeselect/dist/vue-treeselect.css'
  import IconSelect from '@/components/IconSelect'

  export default {
    name: 'Menu',
    components: { Treeselect, IconSelect },
    data() {
      return {
        // 遮罩层
        loading: true,
        // 菜单表格树数据
        menuList: [],
        // 菜单树选项
        menuOptions: [],
        // 弹出层标题
        title: '',
        // 是否显示弹出层
        open: false,
        // 菜单状态数据字典
        statusOptions: [],
        // 缓存数据字典
        cacheOptions: [],
        // 查询参数
        queryParams: {
          name: undefined,
          status: undefined
        },
        // 显示搜索条件
        showSearch: true,
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          name: [
            { required: true, message: this.$t('mechanism.orderNameEmpty'), trigger: 'blur' }
          ],
          sort: [
            { required: true, message: this.$t('mechanism.orderSortEmpty'), trigger: 'change' }
          ],
          path: [
            { required: true, message: this.$t('role.routeAddressEmpty'), trigger: 'blur' }
          ]
        }
      }
    },
    created() {
      this.getList()
      this.getDicts('menu_status').then(response => {
        this.statusOptions = response.data
      })
      this.getDicts('yes_no').then(response => {
        this.cacheOptions = response.data
      })
    },
    methods: {
      // 选择图标
      selected(name) {
        this.form.icon = name
      },
      /** 查询菜单列表 */
      getList() {
        this.loading = true
        listMenu(this.queryParams).then(response => {
          this.menuList = this.handleTree(response.data, 'id')
          this.loading = false
        })
      },
      /** 转换菜单数据结构 */
      normalizer(node) {
        if (node.children && !node.children.length) {
          delete node.children
        }
        return {
          id: node.id,
          label: node.name,
          children: node.children
        }
      },
      /** 查询菜单下拉树结构 */
      getTree() {
        listMenu().then(response => {
          this.menuOptions = []
          const menu = { id: 0, name: this.$t('role.mainCategories'), children: [] }
          menu.children = this.handleTree(response.data, 'id')
          this.menuOptions.push(menu)
        })
      },
      // 菜单显示状态字典翻译
      statusFormat(row, column) {
        if (row.type === 'F') {
          return ''
        }
        return this.selectDictLabel(this.statusOptions, row.status)
      },
      // 取消按钮
      cancel() {
        this.open = false
        this.reset()
      },
      // 表单重置
      reset() {
        this.form = {
          id: undefined,
          parentId: 0,
          name: undefined,
          icon: undefined,
          type: 'M',
          sort: undefined,
          noCache: '1',
          status: '0'
        }
        this.resetForm('form')
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.current = 1
        this.getList()
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm('queryForm')
        this.handleQuery()
      },
      /** 新增按钮操作 */
      handleAdd(row) {
        this.reset()
        this.getTree()
        if (row != null) {
          this.form.parentId = row.id
        }
        this.open = true
        this.title = this.$t('role.addMenu')
      },
      /** 修改按钮操作 */
      handleEdit(row) {
        this.reset()
        this.getTree()
        getMenu(row.id).then(response => {
          this.form = response.data
          this.open = true
          this.title = this.$t('role.changeMenu')
        })
      },
      /** 提交按钮 */
      submitForm: function() {
        this.$refs['form'].validate(valid => {
          if (valid) {
            if (this.form.id !== undefined) {
              editMenu(this.form).then(response => {
                if (response.code === 0) {
                  this.msgSuccess(this.$t('loginLog.changeSuccess'))
                  this.open = false
                  this.getList()
                } else {
                  this.msgError(response.msg)
                }
              })
            } else {
              console.log(JSON.stringify(this.form))
              addMenu(this.form).then(response => {
                if (response.code === 0) {
                  this.msgSuccess(this.$t('addSuccess'))
                  this.open = false
                  this.getList()
                } else {
                  this.msgError(response.msg)
                }
              })
            }
          }
        })
      },
      /** 删除按钮操作 */
      handleDel(row) {
        this.$confirm(this.$t('enterDeleteName') + row.name + this.$t('equipment.deleteEquipment2'), this.$t('warning'), {
          confirmButtonText: this.$t('submitText'),
          cancelButtonText: this.$t('cancelText'),
          type: 'warning'
        }).then(function() {
          return delMenu(row.id)
        }).then(() => {
          this.getList()
          this.msgSuccess(this.$t('deleteSuccess'))
        }).catch(function() {
        })
      }
    }
  }
</script>

